﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Speech;
using System.Speech.Synthesis;
using DTO;
using BUS;

namespace Support_Study_English
{
    public partial class frmDanhSachTuVuaThem : Office2007Form
    {
        #region Attribute
        private List<VOCABULARY> _lsSource;
        //private DataTable _dtSource;
        protected List<VOCABULARY> _lsDel;
        public SpeechSynthesizer _speaker;
        private int _curIndexRow;
        private int _curIndexCol;
        private bool _isEdit;
        #endregion

        #region Properties
        public List<VOCABULARY> LsSource
        {
            get { return _lsSource; }
            set { _lsSource = value; }
        }
        #endregion

        public frmDanhSachTuVuaThem()
        {
            InitializeComponent();
            //_speaker = new SpeechSynthesizer();
            this.gridVocabulary.AutoGenerateColumns = false;
            _isEdit = false;
        }

        private void frmDanhSachTuVuaThem_Load(object sender, EventArgs e)
        {
            DataTable dtSource = FuncOfDatatable.ToDataTable(_lsSource);
            FuncOfDatatable.AddColumn(ref dtSource, "Changed", "System.Boolean");
            FuncOfDatatable.AddColumn(ref dtSource, "IndexOnList", "System.Int16");
            for (int i = 0; i < _lsSource.Count; i++)
            {
                dtSource.Rows[i]["IndexOnList"] = i;
            }
            this.gridVocabulary.DataSource = null;
            this.gridVocabulary.DataSource = dtSource;            
            //this.gridVocabulary.Columns["idTopic"].Visible = false;
            //this.gridVocabulary.Columns["TOPIC"].Visible = false;
            this.gridVocabulary.Columns["chChanged"].Visible = false;
            this.gridVocabulary.Columns["chIndexOnList"].Visible = false;
            //DataGridViewComboBoxColumn clTopic = (DataGridViewComboBoxColumn)this.gridVocabulary.Columns["chTopic"];
            //clTopic.DisplayMember = "Name";
            //clTopic.ValueMember = "idTopic";
            //clTopic.DataSource = TopicBUS.getAllTopics();

            DataGridViewCheckBoxColumn clTwoWordVerb = (DataGridViewCheckBoxColumn) this.gridVocabulary.Columns["chTwoWordVerb"];
            clTwoWordVerb.ValueType = typeof(int);
            this.label3.Text = dtSource.Rows.Count.ToString();
            _lsDel = new List<VOCABULARY>();
            this.hotKey1.AddHotKey("Shift+S");
        }

        private void gridVocabulary_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (this.gridVocabulary.Rows[e.RowIndex].Cells["chChanged"].Value.ToString().Equals(""))
            {
                this.gridVocabulary.Rows[e.RowIndex].Cells["chChanged"].Value = true;
                _isEdit = true;
            }
        }

        private void gridVocabulary_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.gridVocabulary.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in this.gridVocabulary.SelectedRows)
                {
                    _lsDel.Add(_lsSource[int.Parse(row.Cells["chIndexOnList"].Value.ToString())]);
                }
                _curIndexRow = -1;
            }                                        
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Close_Click(object sender, EventArgs e)
        {
            this.gridVocabulary.EndEdit();
            if (_lsDel.Count != 0)
            {
                foreach (VOCABULARY temp in _lsDel)
                {
                    VocabularyBUS.Remove(temp);
                }
            }

            foreach (DataGridViewRow row in this.gridVocabulary.Rows)
            {
                bool change = false;
                if (Boolean.TryParse(row.Cells["chChanged"].Value.ToString(),out change) && change)
                {
                    string word = _lsSource[int.Parse(row.Cells["chIndexOnList"].Value.ToString())].Word;
                    string type = _lsSource[int.Parse(row.Cells["chIndexOnList"].Value.ToString())].Type;
                    int idtopic = _lsSource[int.Parse(row.Cells["chIndexOnList"].Value.ToString())].idTopic;
                    VOCABULARY newVc = new VOCABULARY();
                    newVc.Word = row.Cells["chWord"].Value.ToString();
                    newVc.Type = row.Cells["chType"].Value.ToString();
                    newVc.idTopic = ((TOPIC)row.Cells["chTopic"].Value).idTopic;
                    newVc.Phoneticize = row.Cells["chPhoneticize"].Value.ToString();
                    newVc.MeanEng = row.Cells["chMeanEng"].Value.ToString();
                    newVc.MeanVi = row.Cells["chMeanVi"].Value.ToString();
                    DateTime dateTemp;
                    if (DateTime.TryParse(row.Cells["chDate"].Value.ToString(), out dateTemp))
                    {
                        newVc.Date = dateTemp;
                    }                    
                    short isTwoWord;
                    if (!short.TryParse(row.Cells["chTwoWordVerb"].Value.ToString(), out isTwoWord))
                    {
                        newVc.isTwoWordVerb = 0;
                    }
                    newVc.isTwoWordVerb = isTwoWord;
                    VocabularyBUS.Edit(word, type, idtopic, newVc);
                }
            }
            _isEdit = false;
        }

        //protected string RemoveChar(string str, char c)
        //{
        //    string res = str;
            
        //}

        private void hotKey1_HotKeyPressed(object sender, SmartHotKey.HotKeyEventArgs e)
        {
            if (e.HotKey == "Shift+S")
            {
                //_speaker.Rate = Convert.ToInt32(speedUpDown.Value);
                _speaker.Volume = 100;
                DataGridViewRow row = this.gridVocabulary.Rows[_curIndexRow];
                string word = row.Cells["chWord"].Value.ToString();
                string phoneticize = row.Cells["chPhoneticize"].Value.ToString();               
                ////phoneticize.
                //if (!phoneticize.Equals(""))                
                //{
                //    phoneticize = ChuanHoaPhienAm.XoaTatCaKyTu(phoneticize, '/');
                //    PromptBuilder myPrompt = new PromptBuilder();                                        
                //    myPrompt.AppendTextWithPronunciation(word, phoneticize);                     
                //    _speaker.Speak(myPrompt);
                //}
                //else
                //{
                //    _speaker.Speak(word);
                //}
                _speaker.Speak(word);
            }
            //if (e.HotKey == "Shift+S")
            //{
            //    //_speaker.Rate = Convert.ToInt32(speedUpDown.Value);
            //    _speaker.Volume = 100;
            //    PromptBuilder myPrompt = new PromptBuilder();
            //    myPrompt.AppendTextWithPronunciation(, "rɛdɪŋ");
            //    _speaker.Speak(myPrompt);
            //}
                //DateTime temp = DateTime.Parse(dgvDanhSachTu.Rows[rowIndex].Cells[7].Value.ToString());
                //string fname = "..\\..\\Audio\\Word\\" + temp.Year.ToString() + temp.Month.ToString() + temp.Day.ToString() + '\\' + dgvDanhSachTu.Rows[rowIndex].Cells[0].Value.ToString() + ".mp3";                
                //if (File.Exists(fname))
                //{
                //    Player pl = new Player();
                //    pl.Close();
                //    pl.Open(fname);
                //    pl.Play(false);
                //}
                //else
                //{
                //    MessageBox.Show("The media file does not exist.", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //}
        }
                
        private void gridVocabulary_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            _curIndexRow = e.RowIndex;
            _curIndexCol = e.ColumnIndex;
        }

        private void gridVocabulary_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData.Equals(Keys.Delete) && _curIndexRow != -1)
            {
                _lsDel.Add(_lsSource[int.Parse(this.gridVocabulary.Rows[_curIndexRow].Cells["chIndexOnList"].Value.ToString())]);
                this.gridVocabulary.Rows.RemoveAt(_curIndexRow);
            }
            if (e.KeyData.Equals(Keys.F2) && _curIndexCol == 4)
            {
                DataGridViewRow row = this.gridVocabulary.Rows[_curIndexRow];
                frmEditTopic frm = new frmEditTopic();
                frm.Word = row.Cells["chWord"].Value.ToString();
                frm.Type = row.Cells["chType"].Value.ToString();
                frm.OldTopic = (TOPIC)row.Cells["chTopic"].Value;
                frm.ShowDialog();
                if (frm.IsOk)
                {
                    row.Cells["chTopic"].Value = frm.NewTopic;
                }

            }
        }

        private void gridVocabulary_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                DataGridViewRow row = this.gridVocabulary.Rows[e.RowIndex];
                frmEditTopic frm = new frmEditTopic();
                frm.Word = row.Cells["chWord"].Value.ToString();
                frm.Type = row.Cells["chType"].Value.ToString();
                frm.OldTopic = (TOPIC)row.Cells["chTopic"].Value;                    
                frm.ShowDialog();
                if(frm.IsOk)
                {
                    row.Cells["chTopic"].Value = frm.NewTopic;                    
                }
            }
        }

        private void frmDanhSachTuVuaThem_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isEdit)
            {
                DialogResult result = MessageBox.Show("Bạn có muốn lưu lại không?", "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    this.btnSave_Close.PerformClick();                    
                }
                else
                {
                    if (result == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }                
    }
}
